//
//  WBMainViewController.swift
//  WeiBo
//
//  Created by 今代科技 on 2017/10/16.
//  Copyright © 2017年 GZY. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeButton()
    }
    /**
     portrait    : 竖屏，肖像
     landscape   : 横屏，风景画
     
     - 使用代码控制设备的方向，好处，可以在在需要横屏的时候，单独处理！
     - 设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向！
     - 如果播放视频，通常是通过 modal 展现的！
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    //MARK: - 监听方法
    //FIXME: 没有实现
    // private:保证方法私有, 仅在当前对象访问
    // @objc 允许这个函数在运行时通过 oc 的消息机制调用
    @objc private func buttonClick() -> () {
        print("click button")
        // 测试方向旋转
        let vc = UIViewController() 
        vc.view.backgroundColor = UIColor.zy_random()
        present(vc, animated: true, completion: nil)
    }
  
    //MARK: - 私有控件
    //撰写按钮
   
    private lazy var composeButton = { () -> UIButton in
        
        var button = UIButton(type: .custom)
        button = UIButton.zy_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
        button.frame = CGRect(x: 0, y: 10, width: 30, height: 30)
        button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
        return button
    }()
}
extension WBMainViewController {
    //设置撰写按钮
    private func setupComposeButton () {
        tabBar.addSubview(composeButton)
        let count = (CGFloat)(childViewControllers.count)
        let w = tabBar.bounds.width / count - 1
        // OC == CGRectInset 缩进
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 5)
    }
    
    // 设置所有的子控制器
    private func setupChildControllers() {
        //let arr: [[String : String]]
        
        // 0: 获取沙河json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        // 加载data
        var data = NSData(contentsOfFile: jsonPath)
        // 判断 data是否有内容, 如果没有说明沙河没有文件
        if data == nil {
            // 从bundle加载data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        // data一定会有一个内容, 反序列化
        // 从bundle 加载配置的json
        
        guard let arr = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
            else {
                    return
        }
//        let arr = [
//            ["clsName":"WBHomeViewController","title":"首页","imageName":"_home","visitorInfo":["imageName":"","message":"关注一些人，回这里看看有什么惊喜"]],
//            ["clsName":"WBMessageViewController","title":"消息","imageName":"_order","visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
//            ["clsName":"UIViewController"],
//            ["clsName":"WBDiscoverViewController","title":"发现","imageName":"_money","visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]],
//
//           ["clsName":"WBProfileViewController","title":"我","imageName":"_my","visitorInfo":["imageName":"visitordiscover_image_profile","message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]
//        ]
        // 测试数据格式 - 转换成plist文件
//        (arr as NSArray).write(toFile: "/Users/jipeng/Desktop/demo.plist", atomically: true)
        
        
        // 数组 -> json 序列化
//        let data = try! JSONSerialization.data(withJSONObject: arr, options: .prettyPrinted)
//        (data as NSData).write(toFile: "/Users/jipeng/Desktop/demo.json", atomically: true)
        
        var arrM = [UIViewController]()
        for dic in arr! {
            arrM.append(controller(dic: dic as [String : AnyObject]))
        }
        viewControllers = arrM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dic: 信息字典
    /// - Returns: 子控制器
    private func controller(dic: [String: AnyObject]) -> UIViewController {
        //1. 取得字典内容
        guard let clsName = dic["clsName"] as? String,
            let title = dic["title"] as? String,
            let imageName = dic["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? WBBaseViewController.Type,
            let visitorDic = dic["visitorInfo"] as? [String: String]
            else {
                return UIViewController()
                
        }
        //2. 创建视图控制器
        //1> 将 clsName 转换成cls
        let vc = cls.init()
        vc.title = title
        //设置控制器的访客信息字典
        vc.visitorInfoDic = visitorDic;
        //3.设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //设置 tabbar标题颜色
    vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 12)], for: .normal);
        vc.tabBarController?.tabBar.isTranslucent = false
    vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.red], for: .highlighted)
        let nav = WBNavigationController(rootViewController: vc)
        return nav
        
    }
}
